package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapText;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.FileListAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.LawingSiteE;
import com.infore.airsupervise.bean.MenuE;
import com.infore.airsupervise.bean.PolluterE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.SiteLawingBiz;
import com.infore.airsupervise.biz.impl.SiteLawingBizImpl;
import com.infore.airsupervise.db.SiteLawDBHelper;
import com.infore.airsupervise.http.BaseResponse;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.other.listener.LayoutControl;
import com.infore.airsupervise.other.listener.LayoutControlListener;
import com.infore.airsupervise.ui.fragment.SingnatrueFragment;
import com.infore.airsupervise.ui.widget.ItemDecoration1px;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * @features: 创建现场执法 界面
 * @author: WuTao
 * @date: 2017/5/4 10:29
 */
public class SiteMainCreateActivity extends BaseTitleBarActivity  {
    @BindView(R.id.btn_search)
    AwesomeTextView btnSearch;
    @BindView(R.id.tv_recorder_arrow)
    AwesomeTextView tvRecorderArrow;
    @BindView(R.id.rv_recorder)
    RecyclerView rvRecorder;
    @BindView(R.id.tv_ask_arrow)
    AwesomeTextView tvAskArrow;
    @BindView(R.id.rv_note_ask)
    RecyclerView rvNoteAsk;
    @BindView(R.id.tv_check_arrow)
    AwesomeTextView tvCheckArrow;
    @BindView(R.id.rv_note_check)
    RecyclerView rvNoteCheck;
    @BindView(R.id.tv_evidence_arrow)
    AwesomeTextView tvEvidenceArrow;
    @BindView(R.id.rv_evidence)
    RecyclerView rvEvidence;
    @BindView(R.id.tv_signature_arrow)
    AwesomeTextView tvSignatureArrow;
    @BindView(R.id.ll_signature)
    LinearLayout llSignature;

    private static final int DB_SAVE = 1; //新建时 （保存）
    private static final int DB_UPDATA = 2; //再编辑时 （更新）

    private PolluterE polluterE; //污染源
    //签名布局
    private SingnatrueFragment inspectSignFra ;
    private SingnatrueFragment noteSignFra;
    //布局控制
    private LayoutControlListener layoutControlListener;

    private List<LawingSiteE.RecorderJC> recorderList = new ArrayList<>();
    private List<LawingSiteE.NotesJC> checkList  = new ArrayList<>();
    private List<LawingSiteE.NotesAsk> askList = new ArrayList<>();
    private LawingSiteE.Evidence evidenceE;

    //各部分内容的适配器
    private BaseQuickAdapter<LawingSiteE.RecorderJC, BaseViewHolder> recorderAdapter;
    private BaseQuickAdapter<LawingSiteE.NotesJC, BaseViewHolder> checkAdapter;
    private BaseQuickAdapter<LawingSiteE.NotesAsk, BaseViewHolder> askAdapter;
    private FileListAdapter evidenceAdapter;
    //网络请求
    private SiteLawingBiz siteLawingBiz;
    private LawingSiteE siteE;

    private SiteLawDBHelper dbHelper; //数据库操作类
    private int dbHelperState ; //数据库操作标识
    private String missionId ; //关键的任务id

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sitelawing_create);
        ButterKnife.bind(this);
        Intent it = getIntent();
        if(null != it){
            siteE = (LawingSiteE) it.getSerializableExtra("LawingSiteE");
            missionId = it.getStringExtra("intent_missionId");
        }
        if(null != siteE ){ //再编辑
            dbHelperState = DB_UPDATA;
            initSiteLaw();
        }else { //初次创建
            dbHelperState = DB_SAVE;
            siteE = new LawingSiteE();
            evidenceE = new LawingSiteE.Evidence();
          //  evidenceE.setFiles( new ArrayList<String>());
        }
        layoutControlListener = new LayoutControl(ctx);
        siteLawingBiz = new SiteLawingBizImpl();

        initTitle();
        initRecycleView();
    }

    /**
     * 导航栏
     */
    private void initTitle() {
        title.setText("现场执法记录");
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_SEND_O);
        inspectSignFra = new SingnatrueFragment(siteE.getSignaturePson());
        //执法人员签名
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_singatrue_inspect,inspectSignFra,null).commit();
        //企业人员签名
        noteSignFra = new SingnatrueFragment(siteE.getSignatureCom());
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_singatrue_com,noteSignFra,null).commit();
    }

    /**
     * 设置各个部分列表recyclerView
     */
    private void initRecycleView() {
        //现场检查记录
        rvRecorder.setLayoutManager(new LinearLayoutManager(ctx));
        rvRecorder.addItemDecoration(new ItemDecoration1px(ctx, ItemDecoration1px.VERTICAL_LIST));
        //适配器
        recorderAdapter = new BaseQuickAdapter<LawingSiteE.RecorderJC, BaseViewHolder>(R.layout.item_lawing_site, recorderList) {
            @Override
            protected void convert(final BaseViewHolder helper, final LawingSiteE.RecorderJC item) {
                final int position  = helper.getAdapterPosition();
                helper.setText(R.id.tv_title,"现场监察记录")
                        .setText(R.id.tv_describe,item.getSupervise());
                //子控件点击事件
                View.OnClickListener itemChildClickListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (view.getId()) {
                            case R.id.iv_delete :
                                remove(position);
                                break;
                            case R.id.iv_edit :
                                Bundle bundle = new Bundle();
                                bundle.putInt(Constants.INTENT_INT_KEY,position);
                                bundle.putSerializable(Constants.INTENT_OBJ_KEY,getItem(position));
                                bundle.putSerializable("intent_polluter",polluterE);
                                JumpUtil.ForResultJumpFromTo(SiteMainCreateActivity.this, SiteRecordCreateActivity.class,101,bundle);
                        }
                    }
                };
                //删除
                helper.getView(R.id.iv_delete).setOnClickListener(itemChildClickListener);
                //编辑
                helper.getView(R.id.iv_edit).setOnClickListener(itemChildClickListener);
            }
        };
        recorderAdapter.addFooterView(getFooterView(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtil.showShort(ctx, "添加一个现场监察记录");
                JumpUtil.ForResultJumpFromTo(SiteMainCreateActivity.this,SiteRecordCreateActivity.class,100,"intent_polluter",polluterE);
            }
        }));
        rvRecorder.setAdapter(recorderAdapter);

        //询问笔录
        rvNoteAsk.setLayoutManager(new LinearLayoutManager(ctx));
        rvNoteAsk.addItemDecoration(new ItemDecoration1px(ctx, ItemDecoration1px.VERTICAL_LIST));
        //适配器
        askAdapter = new BaseQuickAdapter<LawingSiteE.NotesAsk, BaseViewHolder>(R.layout.item_lawing_site, askList) {
            @Override
            protected void convert(final BaseViewHolder helper, final LawingSiteE.NotesAsk item) {
                final int position  = helper.getAdapterPosition();
                helper.setText(R.id.tv_title,"询问笔录")
                        .setText(R.id.tv_describe,item.getAnswerName());
                View.OnClickListener itemChildClickListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (view.getId()) {
                            case R.id.iv_delete :
                                remove(position);
                                break;
                            case R.id.iv_edit :
                                Bundle bundle = new Bundle();
                                bundle.putInt(Constants.INTENT_INT_KEY,position);
                                bundle.putSerializable(Constants.INTENT_OBJ_KEY,getItem(position));
                                bundle.putSerializable("intent_polluter",polluterE);
                                JumpUtil.ForResultJumpFromTo(SiteMainCreateActivity.this, SiteAskCreateActivity.class,301,bundle);
                        }
                    }
                };
                //删除
                helper.getView(R.id.iv_delete).setOnClickListener(itemChildClickListener);
                //编辑
                helper.getView(R.id.iv_edit).setOnClickListener(itemChildClickListener);
            }
        };
        askAdapter.addFooterView(getFooterView(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtil.showShort(ctx, "添加一个询问笔录");
                JumpUtil.ForResultJumpFromTo(SiteMainCreateActivity.this, SiteAskCreateActivity.class,300,"intent_polluter",polluterE);
            }
        }));
        rvNoteAsk.setAdapter(askAdapter);

        //检查笔录
        rvNoteCheck.setLayoutManager(new LinearLayoutManager(ctx));
        rvNoteCheck.addItemDecoration(new ItemDecoration1px(ctx, ItemDecoration1px.VERTICAL_LIST));
        checkAdapter = new BaseQuickAdapter<LawingSiteE.NotesJC, BaseViewHolder>(R.layout.item_lawing_site, checkList) {
            @Override
            protected void convert( BaseViewHolder helper, final LawingSiteE.NotesJC item) {
                final int position  = helper.getAdapterPosition();
                helper.setText(R.id.tv_title,"勘察（检查）笔录")
                        .setText(R.id.tv_describe,item.getLeaderName());
                View.OnClickListener itemChildClickListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                            switch (view.getId()) {
                                case R.id.iv_delete :
                                    remove(position);
                                    break;
                                case R.id.iv_edit :
                                    Bundle bundle = new Bundle();
                                    bundle.putInt(Constants.INTENT_INT_KEY,position);
                                    bundle.putSerializable(Constants.INTENT_OBJ_KEY,getItem(position));
                                    bundle.putSerializable("intent_polluter",polluterE);
                                    JumpUtil.ForResultJumpFromTo(SiteMainCreateActivity.this, SiteInspectCreateActivity.class,201,bundle);
                            }

                    }
                };
                //删除
                helper.getView(R.id.iv_delete).setOnClickListener(itemChildClickListener);
                //编辑
                helper.getView(R.id.iv_edit).setOnClickListener(itemChildClickListener);
            }
        };
        checkAdapter.addFooterView(getFooterView(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtil.showShort(ctx, "添加一个勘察（检查）笔录");
                JumpUtil.ForResultJumpFromTo(SiteMainCreateActivity.this, SiteInspectCreateActivity.class,200,"intent_polluter",polluterE);
            }
        }));
        rvNoteCheck.setAdapter(checkAdapter);

        //执法取证
        rvEvidence.setLayoutManager(new LinearLayoutManager(ctx));
        rvEvidence.addItemDecoration(new ItemDecoration1px(ctx, ItemDecoration1px.VERTICAL_LIST));
        evidenceAdapter = new FileListAdapter(R.layout.item_file,evidenceE.getFiles(),true);
        evidenceAdapter.addFooterView(getFooterView(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtil.showShort(ctx, "添加执法取证");
                Bundle bundle = new Bundle();
                bundle.putSerializable("SiteToEvidence" , evidenceE);
                bundle.putSerializable("intent_polluter", polluterE );
                JumpUtil.ForResultJumpFromTo(SiteMainCreateActivity.this, SiteEvidenceCreateActivity.class,400 ,bundle);
            }
        }));
        rvEvidence.setAdapter(evidenceAdapter);
    }

    /**
     * recylceView 的添加布局
     *
     * @param listener
     * @return
     */
    private View getFooterView(View.OnClickListener listener) {
        View foot = getLayoutInflater().inflate(R.layout.layout_site_add_footer, null);
        BootstrapButton btn_add = (BootstrapButton) foot.findViewById(R.id.btn_add);
        btn_add.setOnClickListener(listener);
        return foot;
    }

    /**
     * 设置污染源UI
     */
    private void setPolluterData(PolluterE polluterE){
        if(null != polluterE) {
            BootstrapText.Builder builder = new BootstrapText.Builder(ctx);
            builder.addFontAwesomeIcon(FontAwesome.FA_SEARCH)
                    .addText(" " + polluterE.getName());
            btnSearch.setBootstrapText(builder.build());
            btnSearch.setGravity(Gravity.START);
        }
    }

    /**
     * 设置请求参数
     */
    private void setSiteLaw(){
        siteE.setSignatureCom(noteSignFra.getSignatrueList());
        siteE.setSignaturePson(inspectSignFra.getSignatrueList());
        siteE.setRecorderJCList(recorderList);
        siteE.setNotesAskList(askList);
        siteE.setNotesJCList(checkList);
        siteE.setEvidence(evidenceE);
        //判断污染源
        if(null != polluterE) {
            siteE.setPolluterE(polluterE);
            siteE.setMn(polluterE.getMn());
            siteE.setName(polluterE.getName());
        }
        if(!TextUtils.isEmpty(missionId)){ //关联任务ID
            siteE.setMissionId(missionId);
        }
    }

    /**
     * 再编辑时初始化数据
     */
    private void initSiteLaw(){
        try {
            evidenceE = siteE.getEvidence();
            polluterE = siteE.getPolluterE();
            setPolluterData(polluterE);
            recorderList.addAll(siteE.getRecorderJCList());
            askList.addAll(siteE.getNotesAskList());
            checkList.addAll(siteE.getNotesJCList());
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    /**
     * 提交执法
     */
    private void commitSiteLaw(){
        //loading dialog
        final SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();

        //请求提交业务
        siteLawingBiz.commitSiteLawingRequest(siteE, new OnServerResponseListener<BaseResponse>() {
            @Override
            public void onSucceed(BaseResponse result, String desc) {
                if(dbHelperState == DB_UPDATA){
                    deleteToDB();
                }
                //成功提示dialog
                dialog.setTitleText(MsgConst.OPERATION_SUCCESS)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                                finish();
                            }
                        })
                        .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                //失败提示dialog
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });
    }




    private boolean isRecorderShow;
    private boolean isAskShow;
    private boolean isCheckShow;
    private boolean isEvidenceShow;
    private boolean isSignShow;

    /**
     * 点击事件
     * @param view
     */
    @OnClick({R.id.btn_search, R.id.ll_recorder, R.id.ll_note_ask, R.id.ll_note_check, R.id.ll_evidence, R.id.ll_signature_control})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_search: //污染源搜索
                ToastUtil.showShort(ctx, "选择一个污染源");
                JumpUtil.ForResultJumpFromTo(this, PolluterSearchActivity.class, 99, Constants.INTENT_INT_KEY, 1);
                break;
            case R.id.ll_recorder:
                isRecorderShow = !isRecorderShow;
                layoutControlListener.layoutControl(isRecorderShow, rvRecorder, tvRecorderArrow);
                break;
            case R.id.ll_note_ask:
                isAskShow = !isAskShow;
                layoutControlListener.layoutControl(isAskShow,rvNoteAsk,tvAskArrow);
                break;
            case R.id.ll_note_check:
                isCheckShow = !isCheckShow;
                layoutControlListener.layoutControl(isCheckShow,rvNoteCheck,tvCheckArrow);
                break;
            case R.id.ll_evidence:
                isEvidenceShow = !isEvidenceShow;
                layoutControlListener.layoutControl(isEvidenceShow,rvEvidence,tvEvidenceArrow);
                break;
            case R.id.ll_signature_control:
                isSignShow = !isSignShow;
                layoutControlListener.layoutControl(isSignShow, llSignature,tvSignatureArrow);
                break;
        }
    }

    @Override
    protected void onRightMenuClick(View view) {
        super.onRightMenuClick(view);
        setSiteLaw();
        String str_alarm = "";
        if( null == polluterE){
            str_alarm = "请选择一个污染源，才能提交该执法记录";
            ToastUtil.showLong(ctx,str_alarm);
        }else if(TextUtils.isEmpty(siteE.getMissionId())){
             SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("温馨提示")
                    .setContentText("是否关联待办任务")
                    .setConfirmText("去关联任务")
                    .setCancelText("直接提交")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            MenuE menuE = new MenuE(StatusConst.MISSION_DB, R.drawable.ic_menu_law_db,
                                    "待办任务",null,null);
                            Bundle  bundle = new Bundle();
                            bundle.putSerializable(Constants.INTENT_OBJ_KEY,menuE);
                            bundle.putInt("from",1);
                            JumpUtil.ForResultJumpFromTo(SiteMainCreateActivity.this,NewMissionListActivity.class,bundle,98);
                        }
                    })
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            //提交
                            commitSiteLaw();
                        }
                    });
            dialog.show();
        } else {
            //提交
            commitSiteLaw();
        }

    }

    @Override
    protected void onLeftMenuClick(View view) {
        if(null != siteE && null != polluterE){
            setSiteLaw();
            final SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("温馨提示")
                    .setContentText("是否保存该记录")
                    .setConfirmText("确定")
                    .setCancelText("取消")
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                           finish();
                        }
                    }).setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            if(dbHelperState == DB_SAVE) {
                                saveDataToDB();
                            }else if(dbHelperState == DB_UPDATA){
                                updataTODB();
                            }
                            finish();
                        }
                    });

            dialog.show();
        }else {
            super.onLeftMenuClick(view);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(RESULT_OK == resultCode){
            int position = data.getIntExtra(Constants.INTENT_INT_KEY,-1);
            Object obj =  data.getSerializableExtra(Constants.INTENT_OBJ_KEY);
            if(requestCode == 99){ //从主界面选择污染源
                polluterE = (PolluterE) obj;
                setPolluterData(polluterE);
            }else if( requestCode != 98 ) { //其他界面返回主界面时带污染源
                polluterE = (PolluterE) data.getSerializableExtra("intent_polluter");
                setPolluterData(polluterE);
            }
            if(requestCode == 100){ //现场监察记录返回值
                 recorderAdapter.addData((LawingSiteE.RecorderJC) obj);
            }else if(requestCode == 200){ //现场检查（勘察）笔录
                checkAdapter.addData((LawingSiteE.NotesJC) obj);
            }else if(requestCode == 300 ){//询问笔录
                askAdapter.addData((LawingSiteE.NotesAsk) obj);
            }else if(requestCode == 101){//现场监察记录 编辑修改返回值
                if(-1 != position) {
                    recorderAdapter.setData(position, (LawingSiteE.RecorderJC) obj);
                }
            } else if(requestCode == 201){//现场检查（勘察） 编辑修改笔录
                if(-1 != position){
                    checkAdapter.setData(position,(LawingSiteE.NotesJC) obj);
                }
            }else if(requestCode == 301){ //询问 编辑修改笔录
                if(-1 != position){
                    askAdapter.setData(position,(LawingSiteE.NotesAsk) obj);
                }
            }else if (requestCode == 400) { //执法取证
                evidenceE = (LawingSiteE.Evidence)obj;
                evidenceAdapter.setNewData(evidenceE.getFiles());
            }else if(requestCode == 98 ){ //返回关联任务
                String missionId = data.getStringExtra(Constants.INTENT_STR_KEY);
                siteE.setMissionId(missionId);
                commitSiteLaw();
            }
        }
    }


    private void saveDataToDB(){
        if(null == dbHelper){
            dbHelper = new SiteLawDBHelper(ctx,1,UserE.getUserInfo().getUserId());
        }
        dbHelper.save(siteE);
    }

    private void updataTODB(){
        if(null == dbHelper){
            dbHelper = new SiteLawDBHelper(ctx,1,UserE.getUserInfo().getUserId());
        }
        dbHelper.updata(siteE);
    }
    private void deleteToDB(){
        if(null == dbHelper){
            dbHelper = new SiteLawDBHelper(ctx,1,UserE.getUserInfo().getUserId());
        }
        dbHelper.delete(siteE);
    }
}
